package com.example.demo.auth.config;

import com.example.demo.auth.JwtAuthenticationFilter;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    public void configure(WebSecurity web) {
        // @formatter:off
        // 权限忽略url
        web.ignoring()
                .antMatchers(
                        "/error",
                        "/app/file/**",
                        "/app/common/**",
                        "/**/js/**",
                        "/**/imgs/**",
                        "/**/css/**",
                        "/webjars/**",
                        "swagger-ui.html",
                        "doc.html",
                        "**/swagger-ui.html",
                        "/swagger-resources/**",
                        "/v2/**",
                        "/**/*.ttf")
                .antMatchers("/api/**",
                        "/netCarCertificate/**",
                        "/app/file/**",
                        "/app/common/**",
                        "/v2/api-docs",
                        "/swagger-resources/configuration/ui",
                        "/swagger-resources",
                        "/swagger-resources/configuration/security",
                        "/swagger-ui.html")
                .antMatchers("/test/**");  //业务api接口访问控制;
        // @formatter:on
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable().authorizeRequests()
                .antMatchers("/*").permitAll()
//                .antMatchers(HttpMethod.POST, "/login").permitAll()
                .anyRequest().authenticated()
                .and()
                // We filter the api/** requests
                .addFilterBefore(new JwtAuthenticationFilter(),
                        UsernamePasswordAuthenticationFilter.class);
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()
                .withUser("admin").password("admin").roles("USER").and()
                .withUser("admin2").password("admin2").roles("USER");
    }


}
